package com.example.rpc;

import com.example.protocol.PackMsg;
import com.example.protocol.ReqBody;
import com.example.protocol.ReqHeader;
import com.example.protocol.RespBody;
import com.example.serialization.SeriaUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class ServerDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {

        while (buf.readableBytes() >= 100) {
            byte[] bytes = new byte[100];
            buf.getBytes(buf.readerIndex(), bytes);

            ReqHeader reqHeader = (ReqHeader) SeriaUtil.decode(bytes);

            if (buf.readableBytes() >= reqHeader.getDataLen() + 100) {
                buf.readBytes(100);

                byte[] bytes1 = new byte[(int) reqHeader.getDataLen()];
                buf.readBytes(bytes1);
                int flag = reqHeader.getFlag();
                if (flag == 0x14141414) {

                    ReqBody reqBody = (ReqBody) SeriaUtil.decode(bytes1);

                    PackMsg packMsg = new PackMsg();
                    packMsg.setReqBody(reqBody);
                    packMsg.setHeader(reqHeader);

                    out.add(packMsg);

                } else if (flag == 0x14141424) {

                    RespBody respBody = (RespBody) SeriaUtil.decode(bytes1);

                    PackMsg packMsg = new PackMsg();
                    packMsg.setRespBody(respBody);
                    packMsg.setHeader(reqHeader);

                    out.add(packMsg);

                }

            } else {

                break;
            }


        }

    }
}
